import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form} from 'antd';
import PropTypes from 'prop-types';
import routes from '../routes';
import {FORM_OPTIONS, TABLE, FIXED_COLUMN_WIDTH} from '../../constants';
import {PERMISSION} from '../constants';
import {hasPermissions} from '../utils';
import {injectIntl} from '../intl';
import styles from '../style.css';
import TextInput from 'Shared/components/TextInput';
import Return from '../../common/Return';
import {newOrUpdateNoticeProgramValidator} from '../validator';
import {getNoticeProgramsDetail} from '../api';
import PersonnelSelectPanel from './PersonnelSelectPanel';
import WrappedPopconfirm from '../../common/WrappedPopconfirm';
const FormItem = Form.Item;
class NoticeProgramNewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        details: [],
        showPersonnelSelectPanel: false,
    }
    componentDidMount() {
        this.getNoticeProgramsDetail();
    }
    
    componentWillUnmount() {
        this.isunmount = true;
    }
    getNoticeProgramsDetail = () => {
        if(this.props.id)
            getNoticeProgramsDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            isFetching: false,
                            data: res.data,
                            details: res.data.details
                        });
                    else
                        this.setState(({
                            isFetching: false
                        }));
                });
    }
    removeFilePath = file => {
        const data = this.state.data;
        const index = data.attachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const attachments = data.attachments || [];
        attachments.splice(index, 1);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onChangeUpload = value => {
        const data = this.state.data;
        const attachments = data.attachments || [];
        attachments.push(value[0]);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onPersonnelDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true
        });
    }
    onPersonnelDeleteAddedItem = e => {
        const addedItemId = e.target.dataset.id;
        const tmp = this.state.details.filter(d => d.responsiblerId !== addedItemId);
        this.setState({
            details: [...tmp],
            hasOperat: true
        });
    }
    onClickSearchPersonnelBtn = () => {
        this.setState({
            showPersonnelSelectPanel: true,
        });
    }
    onClosePersonnelSelectPanel = () => {
        this.setState({showPersonnelSelectPanel: false});
    }
    onSelectAddedPersonnel = records => {
        const addedItems = this.state.details || [];
        records.forEach(r => {
            const index = addedItems.findIndex(v => v.responsiblerId === r.id);
            if(index === -1)
                addedItems.push({
                    responsiblerId: r.id,
                    responsiblerName: r.name,
                });
        });
        this.setState({
            details: [...addedItems],
            hasOperat: true,
            showPersonnelSelectPanel: false
        });
    }
    onSubmit = () => {
        const {data, details} = this.state;
        const isValid = newOrUpdateNoticeProgramValidator(data, details);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmit(data, details).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }

    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, loading} = this.state;
        const validateName = !data.name && this.state.validate ? 'error' : null;
        const submitable = !hasPermissions(PERMISSION.add, this.props.permissions) || !hasPermissions(PERMISSION.update, this.props.permissions);
        const columns = [{
            title: formatMessage({
                id: 'noticeProgramNewPanel.column.responsiblerId',
                defaultMessage: '人员'
            }),
            dataIndex: 'responsiblerName',
            render: (text, record) => record.responsiblerName
        }, {
            title: details && details.length ? (
                <WrappedPopconfirm
                    id="noticeProgramNewPanel.personnel.delete"
                    title={this.props.intl.formatMessage({
                        id: 'noticeProgramNewPanel.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'noticeProgramNewPanel.personnel.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'noticeProgramNewPanel.personnel.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.onPersonnelDeleteAll}>
                    <a>
                        {this.props.intl.formatMessage({
                            id: 'noticeProgramNewPanel.personnel.deleteAll',
                            defaultMessage: '清空'
                        })}
                    </a>
                </WrappedPopconfirm>
            ) : null,
            dataIndex: 'responsiblerId',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: (text, record) => (
                <a onClick={this.onPersonnelDeleteAddedItem} data-id={text}>
                    {this.props.intl.formatMessage({
                        id: 'noticeProgramNewPanel.part.delete',
                        defaultMessage: '删除'
                    })}
                </a>
            )
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'noticeProgramNewPanel.column.title',
                        defaultMessage: '栏目管理基本信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'noticeProgramNewPanel.operation.code',
                                            defaultMessage: '编号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatMessage({
                                            id: 'noticeProgramNewPanel.title.code',
                                            defaultMessage: '尚未生成'
                                        })}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'noticeProgramNewPanel.operation.name',
                                            defaultMessage: '名称'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateName}
                                        required>
                                        {this.props.id ? data.name
                                            : <TextInput
                                                name="name"
                                                value={data.name}
                                                onBlur={this.onChange} />}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'noticeProgramNewPanel.personnel',
                            defaultMessage: '人员清单'
                        })}
                        extra={<Button size="small" onClick={this.onClickSearchPersonnelBtn}>
                            {this.props.intl.formatMessage({
                                id: 'noticeProgramNewPanel.personnel.addDetail',
                                defaultMessage: '新增清单'
                            })}</Button>}>
                        <Table
                            className="white-space-nowrap"
                            columns={columns}
                            rowKey="responsiblerId"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'noticeProgramNewPanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                {
                    this.state.showPersonnelSelectPanel &&
                    <PersonnelSelectPanel
                        selectKey={data.id}
                        onCancel={this.onClosePersonnelSelectPanel}
                        onSelect={this.onSelectAddedPersonnel} />
                }
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NoticeProgramNewPanel.propTypes = {
    initEnum: PropTypes.object.isRequired,
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    tableNoticeProgramSearch,
    onNoticeNewOrUpdate
} from '../actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getInitData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const programs = initData.programs ? initData.programs.map(item => ({
            text: `${item.name}`,
            value: item.id
        })) : [];
        return {
            programs
        };
    }
);

const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    permissions: getPermissions(state),
    initEnum: getInitData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (data, details) => dispatch(onNoticeNewOrUpdate(data, details)),
    successReturn: () => {
        dispatch(tableNoticeProgramSearch());
        props.history.push(routes.noticeProgram.url());
    },
    onCancel: () => {
        props.history.push(routes.noticeProgram.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NoticeProgramNewPanel));
